﻿using Avalonia.MusicStore.Models;
using DynamicData;
using ReactiveUI;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Input;

namespace Avalonia.MusicStore.ViewModels
{
    public class MainWindowViewModel : ViewModelBase
    {
        public ICommand BuyMusicCommand { get; }
        public Interaction<MusicStoreViewModel, ObservableCollection<AlbumViewModel>> ShowDialog { get; }
        public ObservableCollection<AlbumViewModel> Albums { get; } = new();
        public MainWindowViewModel() 
        {
            BuyMusicCommand = ReactiveCommand.CreateFromTask(async () =>  
            {
                var store = new MusicStoreViewModel();
                var result = await ShowDialog.Handle(store);
                if (result != null && result.Count > 0)
                {
                    foreach (var album in result)
                    {
                        album.ValidationName();
                        Albums.Add(album);
                        
                        await album.SaveToDiskAsync();
                    } 
                }
            });
            ShowDialog = new Interaction<MusicStoreViewModel, ObservableCollection<AlbumViewModel>>();
            RxApp.MainThreadScheduler.Schedule(LoadAlbums);
        }

        private async void LoadAlbums()
        {
            var albums = (await Album.LoadCachedAsync()).Select(x => new AlbumViewModel(x));
            foreach (var album in albums)
            {
                Albums.Add(album);
            }
            foreach (var album in Albums.ToList())
            {
                await album.LoadCover();
            }
        }
    }
}
